import os

from langchain.agents import create_openai_functions_agent, AgentExecutor, create_react_agent
from langchain_openai import ChatOpenAI
from langchain.tools import Tool
import requests
import json

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder


# 1. 定义工具（高德天气示例，需替换为你的真实 API Key）
def get_weather_tool(city: str) -> str:
    """调用高德天气 API 获取天气数据"""
    url = "https://restapi.amap.com/v3/weather/weatherInfo"
    params = {
        "key": "a8e071ea4191909fdc72d54989c89169",  # Key
        "city": city,
        "extensions": "base"  # 基础天气
    }
    try:
        res = requests.get(url, params=params, timeout=5)
        res.raise_for_status()
        data = res.json()
        if data.get('status') != '1':
            return f"获取天气失败：{data.get('info', '未知错误')}"
        return json.dumps(data['lives'][0], ensure_ascii=False)
    except Exception as e:
        return f"请求异常：{str(e)}"


# 2. 注册工具
weather_tool = Tool(
    name="get_weather",
    func=get_weather_tool,
    description="查询指定城市的实时天气，入参为城市名称（如：北京）"
)

# 3. 初始化 LLM 和 Agent
llm = ChatOpenAI(
    model_name="qwen-max",
    api_key = os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    temperature=0.5
)


# 4. 创建 Agent
from langchain import hub
from langchain.agents import AgentExecutor, create_react_agent


class WeatherAgent:
    _agent = None

    @classmethod
    def get_agent(cls):
        if not cls._agent:
            # 使用 LangChain Hub 提供的标准 ReAct 提示模板
            prompt = hub.pull("hwchase17/react")

            # 创建 ReAct Agent
            react_agent = create_react_agent(
                llm=llm,
                tools=[weather_tool],
                prompt=prompt
            )

            cls._agent = AgentExecutor(
                agent=react_agent,
                tools=[weather_tool],
                verbose=True,
                handle_parsing_errors=True
            )
        return cls._agent


# 对外暴露便捷调用函数
def query_weather(city: str) -> str:
    agent = WeatherAgent.get_agent()
    result = agent.invoke({"input": f"查询{city}的天气"})
    if "output" in result:
        return result["output"]
    elif "intermediate_steps" in result:
        last_step = result["intermediate_steps"][-1]
        return last_step[1]  # 返回工具的直接输出
    return "未获取到有效结果"
